<template>
    <div class="apply-service">
        <div v-show="isServer == 0" class="apply">
            <div class="title-radio">
                <div class="title">申请服务商</div>
                <el-radio v-model="titleRadio" label="1" @input="titleRadioInput">企业服务商</el-radio>
                <el-radio v-model="titleRadio" label="2" @input="titleRadioInput">个人服务商</el-radio>
            </div>
            <div class="form">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="155px" class="demo-ruleForm">

                    <el-form-item label="联系人" prop="true_name">
                        <div v-if="isOrder">{{ ruleForm.true_name }}</div>
                        <el-input v-else v-model="ruleForm.true_name" placeholder="请输入联系人"></el-input>
                    </el-form-item>
                    <el-form-item required label="联系电话" prop="tel">
                        <div v-if="isOrder">{{ ruleForm.tel }}</div>
                        <el-input v-else v-model="ruleForm.tel" placeholder="请输入联系电话"></el-input>
                    </el-form-item>

                    <el-form-item label="服务类目" prop="service_cate">
                        <div class="flex-center-1">
                            <div v-if="isOrder">
                                {{ ruleForm.service_cate_name }}
                            </div>
                            <el-select v-else v-model="ruleForm.service_cate" style="width: 327px" class="select"
                                placeholder="请选择服务项目">
                                <el-option v-for="(item, index) in serviceCateList" :key="index" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                            <div class="tip" style="margin-left: 40px; margin-bottom: 0"
                                @click="goServiceHelp('allCate')">
                                查看服务类目
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="所在地区" prop="address">
                        <div v-if="isOrder">{{ ruleForm.city }}</div>
                        <el-cascader v-else ref="address" style="width: 327px" class="select" v-model="ruleForm.address"
                            :options="region" :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                            }" clearable @change="addressChange"></el-cascader>
                    </el-form-item>
                    <el-form-item label="服务商类型" prop="type">
                        <div>{{ ruleForm.type_name }}</div>
                        <!-- <el-radio-group
                            v-else
                            v-model="ruleForm.type"
                            class="serviceType"
                        >
                            <el-radio label="1" border :disabled="isGF">
                                官方服务商
                            </el-radio>
                            <el-radio label="5" border> 普通服务商 </el-radio>
                            <div class="tip" @click="goServiceHelp('allCost')">
                                查看服务商权益
                            </div>
                        </el-radio-group> -->
                    </el-form-item>
                    <el-form-item label="联系人身份证正反面" prop="license">
                        <div style="display: flex">
                            <div>
                                <el-image v-if="isOrder" style="width: 237px; height: 150px" fit="cover"
                                    :src="ruleForm.license" :preview-src-list="[ruleForm.license]">
                                </el-image>
                                <el-upload v-else class="avatar-uploader avatar-uploader-gl" :action="imgUploadUrl" :show-file-list="false"
                                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                    :headers="header">
                                    <img v-if="ruleForm.license" :src="ruleForm.license" class="avatar" />
                                    <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                                    <img v-else src="~/assets/images/openaccount/sfz-1.png" class="upbj" alt="" />
                                </el-upload>
                            </div>
                            <div style="margin-left: 15px">
                                <el-image v-if="isOrder" style="width: 237px; height: 150px" fit="cover"
                                    :src="ruleForm.logo" :preview-src-list="[ruleForm.logo]">
                                </el-image>
                                <el-upload v-else class="avatar-uploader avatar-uploader-gl" :action="imgUploadUrl" :show-file-list="false"
                                    :on-success="handleAvatarSuccess3" :before-upload="beforeAvatarUpload"
                                    :headers="header">
                                    <img v-if="ruleForm.logo" :src="ruleForm.logo" class="avatar" />
                                    <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                                    <img v-else src="~/assets/images/openaccount/sfz-2.png" class="upbj" alt="" />
                                </el-upload>
                            </div>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item>
                        <div slot="label" class="bzj">
                            服务商保证金
                            <el-tooltip class="item" effect="dark" content="详情请查看服务商类目" placement="top">
                                <i class="el-icon-warning-outline"></i>
                            </el-tooltip>
                        </div>
                        <div class="money">
                            {{ isOrder ? ruleForm.cash_deposit : costNum
                            }}<span>元</span>
                        </div>
                    </el-form-item>
                    <el-form-item v-show="costNum > 0">
                        <template slot="label">
                            <i class="el-icon-full-screen"></i>扫码支付
                        </template>
<div class="pay-code">
    <div class="pay">
        <el-radio v-model="ruleForm.pay_type" label="1" :border="true">
            <img src="~/assets/images/service/zfb.png" alt="" />
            支付宝
        </el-radio>
        <el-radio v-model="ruleForm.pay_type" label="2" :border="true">
            <img src="~/assets/images/service/wx.png" alt="" />
            微&emsp;信
        </el-radio>
    </div>
    <div class="fwsxy">
        支付即同意《<span style="cursor: pointer" @click="goService">服务商协议</span>》
    </div>
</div>
</el-form-item> -->
                </el-form>
            </div>
            <div class="form-button">
                <el-button class="submit" type="primary" @click="submitForm('ruleForm')">
                    申请服务商
                </el-button>
            </div>
        </div>
        <div v-show="isServer == 1" class="applying">
            <el-result icon="success" title="  恭喜您！成为服务商" subTitle="">
                <template v-if="showForm" slot="extra">
                    <div class="service-info">
                        <div class="info-item">
                            <div class="label">登录账号：</div>
                            <div class="input">
                                <el-input placeholder="请输入内容" v-model="username" :disabled="true">
                                </el-input>
                            </div>
                            <div class="but">
                                <el-button size="mini" type="primary" plain @click="clone(username)">
                                    复制
                                </el-button>
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="label">初始密码：</div>
                            <div class="input">
                                <el-input placeholder="请输入内容" v-model="password" :disabled="true">
                                </el-input>
                            </div>
                            <div class="but">
                                <el-button size="mini" type="primary" plain @click="clone(password)">
                                    复制
                                </el-button>
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="label">服务商后台网址：</div>
                            <div class="input">
                                <el-input placeholder="请输入内容" v-model="adminUrl" :disabled="true">
                                </el-input>
                            </div>
                            <div class="but">
                                <el-button size="mini" type="primary" plain @click="clone(adminUrl)">
                                    复制
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <div class="zxkf">
                        有问题？<i class="el-icon-headset" @click="goKefu">咨询客服</i>
                    </div>
                </template>
            </el-result>
        </div>
        <div v-show="isServer == 2" class="applying">
            <el-result icon="warning" title="审核中…" subTitle="您的申请已成功提交，会在1-3个工作日内审核完毕，请留意！">
                <template slot="extra">
                    <div class="zxkf">
                        有问题？
                        <i class="el-icon-headset" @click="goKefu" style="cursor: pointer">咨询客服</i>
                    </div>
                </template>
            </el-result>
        </div>

        <div v-html="payHtml"></div>
        <el-dialog title="微信支付" :visible.sync="iframeShow" width="400px" center :close-on-click-modal="false"
            :close-on-press-escape="false" :show-close="false">
            <div class="wxpay">
                <iframe class="iframe" :src="iframeSrc" naem="newPage" />
            </div>
            <span slot="footer" class="dialog-footer">
                <div class="wx-pay-back" @click="closeShow">返回</div>
            </span>
        </el-dialog>

        <div style="opacity: 0; height: 0" id="copycode">{{ cloneText }}</div>
    </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import region from "@/assets/json/region-just-city.json";

import {
    getallcate,
    applyService,
    getPayData,
    getUserpass,
    get_checktype,
    getall_cost,
    getapplyinfo,
} from "@/assets/api/service";
import { userGetUserInfo } from "@/assets/api/indexApi";

import axios from "axios";
import { getServiceType } from "@/assets/utils/utils";

var checkMobile = (rule, value, callback) => {
    if (!value) {
        return callback(new Error("请输入手机号"));
    }
    // var reg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
    var reg = /^1[3456789]\d{9}$/;
    if (!reg.test(value)) {
        return callback(new Error("手机号码有误"));
    } else {
        return callback();
    }
};

var times = null;
export default {
    components: {},
    head() {
        return {
            title: "成为服务商-【小竹财税平台】",
            meta: [
                {
                    hid: "keywords",
                    name: "keywords",
                    content: "小竹财税,服务商,小竹企服",
                },
            ],
        };
    },
    layout: "serverHome",
    data() {
        return {
            titleRadio: '2',
            isGF: true, // 是否有官方服务商 true 有
            applyType: 1,
            region: [],
            ruleForm: {
                name: "",
                address: "",
                city: "",
                license: "",
                qualLlicense: "",
                logo: "",
                true_name: "",
                tel: "",
                service_cate: '',
                pay_type: "1",
                type: "6", // 服务商等级
                service_cate_name: "",
                type_name: "个人服务商",
                cash_deposit: "",
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入企业名称",
                        trigger: "blur",
                    },
                ],
                license: [
                    {
                        required: true,
                        message: "请上传身份证正反面",
                        trigger: "change",
                    },
                ],
                logo: [
                    {
                        required: true,
                        message: "请上传公司logo",
                        trigger: "change",
                    },
                ],
                true_name: [
                    {
                        required: true,
                        message: "请输入联系人",
                        trigger: "blur",
                    },
                ],
                type: [
                    {
                        required: true,
                        message: "请选择服务商等级",
                        trigger: "blur",
                    },
                ],
                tel: [{ validator: checkMobile, trigger: "blur" }],
                address: [
                    {
                        required: true,
                        message: "请选择所在地区",
                        trigger: "change",
                    },
                ],
                service_cate: [
                    {
                        required: true,
                        message: "请选择服务项目",
                        trigger: "change",
                    },
                ],
            },
            serviceCateList: [],
            imgUploadUrl: "",
            payHtml: "",

            username: "",
            password: "",
            adminUrl: "",
            cloneText: "",

            iframeSrc: "",
            iframeShow: false,

            showForm: true,
            token: "",

            allCost: {
                "1_margin": "0",
                "1_upkeep": "0",
                "2_margin": "0",
                "2_upkeep": "0",
                "3_margin": "0",
                "3_upkeep": "0",
                "4_margin": "0",
                "4_upkeep": "0",
                "5_margin": "0",
                "5_upkeep": "0",
                "6_margin": "0",
                "6_upkeep": "0",
            },
            // costNum: 0,

            isOrder: false,
            switchApplyService: true,
        };
    },
    watch: {
        userInfo(newVal, oldVal) {
            if (newVal.is_server == 1) {
                this.getUserpass();
            }
        },
    },
    beforeMount() {
        // this.$options.components["Vcode"] = () => import("vue-puzzle-vcode");
    },
    created() {
        if (this.$route.query.id)
            // 打开订单模式
            this.isOrder = true;
    },
    mounted() {
        this.token = localStorage.getItem("token");
        if (this.token) {
            this.getUserInfo();
            this.init();
        } else {
            this.$alert("请登录", "请登录后查看", {
                confirmButtonText: "确定",
                callback: (action) => {
                    this.$router.push({ path: "/" });
                },
            });
        }
        // ap = require('@/utils/alipayjsapi.min.js')
    },
    computed: {
        ...mapState("common", {
            userInfo: (state) => state.userInfo,
        }),

        costNum() {
            if (!this.ruleForm.type) return;
            return (
                Number(this.allCost[this.ruleForm.type + "_margin"]) +
                Number(this.allCost[this.ruleForm.type + "_upkeep"])
            );
        },

        //上传图片的请求头
        header() {
            return {
                token: this.userInfo && this.token ? this.token : "",
            };
        },
        isServer() {
            return this.userInfo && this.userInfo.is_server
                ? this.userInfo.is_server
                : 0;
        },
    },
    beforeDestroy() {
        if (times) {
            clearTimeout(times);
        }
    },
    methods: {
        ...mapMutations("common", ["setuserInfo"]),
        ...mapActions("common", ["getUserInfo", "getUserInfo2"]),

        titleRadioInput() {
            if (this.titleRadio == '1') {
                this.$router.push({
                    path: '/service/applyservice'
                })
            }
        },

        init() {
            this.getall_cost();
            this.imgUploadUrl = axios.defaults.baseURL + "/api/common/upload";
            this.getCate();
            let regionList = region;
            for (let items of regionList) {
                for (let item of items.children) {
                    delete item.children;
                }
            }
            this.region = regionList;
        },

        async getCate() {
            const res = await getallcate({});
            if (res.code == 1) {
                this.serviceCateList = res.data;
                this.getUserInfo2().then((user) => {
                    if (this.$route.query.id && user.is_server == 0) {
                        this.getapplyinfo();
                    } else {
                        this.isOrder = false;
                    }
                });
            }
        },

        // 获取服务商保证金和服务维护费
        async getall_cost() {
            const res = await getall_cost({});
            if (res.code == 1) {
                this.allCost = res.data;
            }
        },

        // changType(type) {},

        submitForm(formName) {
            // console.log(this.ruleForm.address);
            // return;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // if (this.costNum > 0) {
                    // this.applyService();
                    // } else {
                    this.applyService(false);
                    // }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },

        // 有id 获取id 对应的订单详情
        async getapplyinfo() {
            const res = await getapplyinfo({
                apply_id: this.$route.query.id,
            });
            if (res.code == 1) {
                this.ruleForm.name = res.data.name;
                this.ruleForm.license = res.data.info_images;
                this.ruleForm.qualLlicense = res.data.qual_llicense;
                this.ruleForm.logo = res.data.logo;
                this.ruleForm.true_name = res.data.true_name;
                this.ruleForm.tel = res.data.tel;
                this.ruleForm.service_cate = res.data.service_cate_id;
                this.ruleForm.city = res.data.city;
                this.ruleForm.type = res.data.type + "";
                this.ruleForm.type_name = getServiceType(res.data.type);
                this.ruleForm.address = [
                    Number(
                        res.data.city_code[0] + res.data.city_code[1] + "0000"
                    ),
                    Number(res.data.city_code),
                ];
                this.ruleForm.city = res.data.city;
                this.ruleForm.cash_deposit = res.data.cash_deposit;
                for (let item of this.serviceCateList) {
                    if (item.id == res.data.service_cate_id) {
                        this.ruleForm.service_cate_name = item.name;
                    }
                }
            }
        },

        async applyService(is = true) {
            if (!this.switchApplyService) return;
            this.switchApplyService = false;
            if (this.isOrder && is) {
                const res2 = await getPayData({
                    order_id: this.$route.query.id,
                    source: "web",
                    pay_type: this.ruleForm.pay_type,
                });
                this.switchApplyService = true;

                if (res2.code == 1) {
                    if (this.ruleForm.pay_type == 1) {
                        this.payHtml = res2.data;
                        this.$nextTick(() => {
                            document.forms[1].submit();
                        });
                    } else {
                        // window.open(res2.data, "_blank");
                        this.iframeSrc = res2.data;
                        this.iframeShow = true;
                        this.getWxPayType();
                    }
                }
                return;
            }
            let address = this.$refs.address.getCheckedNodes(true);
            let parems = {
                name: this.userInfo.nickname,
                // info_images: this.ruleForm.license,
                true_name: this.ruleForm.true_name,
                tel: this.ruleForm.tel,
                city_code: address[0].value,
                city: address[0].pathLabels[0] + "-" + address[0].pathLabels[1],
                service_cate_id: '12',
                pay_type: this.ruleForm.pay_type,
                type: '6',
                // qual_llicense: this.ruleForm.qualLlicense,
                logo: this.userInfo.avatar,
                info_images: this.ruleForm.license + "," + this.ruleForm.logo,
            };

            const res = await applyService(parems);
            this.switchApplyService = true;

            if (res.code == 1) {
                if (is == false) {
                    this.getWxPayType();
                    return;
                }
                const res2 = await getPayData({
                    order_id: res.data.order_id,
                    source: "web",
                });
                if (res2.code == 1) {
                    if (this.ruleForm.pay_type == 1) {
                        this.payHtml = res2.data;
                        this.$nextTick(() => {
                            document.forms[1].submit();
                        });
                    } else {
                        // window.open(res2.data, "_blank");
                        this.iframeSrc = res2.data;
                        this.iframeShow = true;
                        this.getWxPayType();
                    }
                }
            }
        },
        async getWxPayType() {
            const res = await userGetUserInfo({});
            if (res.code == 1) {
                if (res.data.is_server != 0) {
                    this.iframeShow = false;
                    this.iframeSrc = "";
                    this.setuserInfo(res.data);
                } else {
                    times = setTimeout(() => {
                        this.getWxPayType();
                    }, 2000);
                }
            }
        },

        // 获取服务商账号密码
        async getUserpass() {
            const res = await getUserpass({});
            if (res.code == 1) {
                if (res.data == "") {
                    this.showForm = false;
                } else {
                    this.username = res.data.username;
                    this.password = res.data.password;
                    this.adminUrl = res.data.service_url;
                }
            }
        },

        async addressChange(item) {
            const res = await get_checktype({
                city_code: item[1],
            });
            if (res.code == 1) {
                if (res.data.length > 0) {
                    this.isGF = true;
                } else {
                    this.isGF = false;
                }
            }
        },

        // 复制
        clone(text) {
            this.cloneText = text;
            this.$nextTick(() => {
                const range = document.createRange();
                range.selectNode(document.getElementById("copycode")); //获取复制内容的 id 选择器
                const selection = window.getSelection(); //创建 selection对象
                if (selection.rangeCount > 0) selection.removeAllRanges(); //如果页面已经有选取了的话，会自动删除这个选区，没有选区的话，会把这个选取加入选区
                selection.addRange(range); //将range对象添加到selection选区当中，会高亮文本块
                document.execCommand("copy"); //复制选中的文字到剪贴板
                selection.removeRange(range); // 移除选中的元素
            });
        },

        handleAvatarSuccess(res, file) {
            // console.log(res, file);
            this.ruleForm.license = res.data.fullurl;
        },
        handleAvatarSuccess2(res, file) {
            // console.log(res, file);
            this.ruleForm.qualLlicense = res.data.fullurl;
        },
        handleAvatarSuccess3(res, file) {
            // console.log(res, file);
            this.ruleForm.logo = res.data.fullurl;
        },
        beforeAvatarUpload(file) {
            const isType =
                file.type == "image/jpeg" ||
                file.type == "image/jpg" ||
                file.type == "image/png";
            const isLtMB = file.size / 1024 / 1024 < 0.5;

            if (!isType) {
                this.$message.error("上传头像图片只能是 JPG,JPEG,PNG 格式!");
            }
            if (!isLtMB) {
                this.$message.error("上传头像图片大小不能超过 500kb!");
            }
            return isType && isLtMB;
        },

        goKefu() {
            let { href } = this.$router.resolve({
                path: "/chatlink",
            });
            window.open(href, "_blank");
        },

        goService() {
            // window.open(
            //   "https://api.xiaozhucaishui.com/xieyi/service.html",
            //   "_blank"
            // );
            let { href } = this.$router.resolve({
                path: "/ServiceAgreement",
                query: {
                    index: 0,
                },
            });
            window.open(href, "_blank");
        },
        closeShow() {
            this.iframeShow = false;
            if (times) {
                clearTimeout(times);
            }
        },

        goServiceHelp(path) {
            let routeUrl = this.$router.resolve({
                path: "/service/servicehelp",
                query: {
                    type: path,
                },
            });

            window.open(routeUrl.href, "_blank");
        },
    },
};
</script>

<style lang="scss" scoped>
.wxpay {
    display: flex;
    align-items: center;
    justify-content: center;

    .iframe {
        width: 333px;
        height: 333px;
        border-width: 0;
    }
}

.wx-pay-back {
    cursor: pointer;
    color: #1c87f3;
}

.apply-service {
    width: 1200px;
    margin: 30px auto;
    background: #ffffff;
    position: relative;
    z-index: 10;
}

.apply {
    padding: 42px 0;
    padding-bottom: 0;

    .title-radio {
        display: flex;
        align-items: center;
        justify-content: center;

        .title {
            font-weight: 600;
            font-size: 22px;
            color: #020C17;
            margin-right: 12px;
            position: relative;
            top: -3px;
        }
    }

    .form-button {
        height: 190px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-top: 1px solid #e8e8e8;

        .submit {
            margin: 0 auto;
            width: 194px;
            height: 58px;
            background: #1c87f3;
        }
    }
}

.form {
    padding: 53px 170px;
    padding-bottom: 0;

    .avatar-uploader-gl{
        line-height: 0;
        .upbj{
            height: 120px;
            width: auto;
        }
         &::v-deep .el-upload {
            border: none !important;
        }
    }

    .avatar-uploader {
        &::v-deep .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
    }

    .avatar-uploader {
        &::v-deep .el-upload:hover {
            border-color: #409eff;
        }
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 237px;
        height: 150px;
        line-height: 150px;
        text-align: center;
    }

    .avatar {
        width: 237px;
        height: 150px;
        display: block;
    }

    .select {
        width: 100%;
    }

    .money {
        font-size: 28px;
        color: #fa5151;

        span {
            font-size: 14px;
            color: #333333;
        }
    }

    .el-icon-full-screen {
        font-size: 14px;
        padding-right: 5px;
    }

    .pay-code {
        display: flex;
        align-items: flex-end;
    }

    .pay {
        text-align: center;
        margin-right: 49px;
        display: flex;
        align-items: center;

        img {
            vertical-align: middle;
            width: 20px;
            height: 20px;
            padding-right: 5px;
        }
    }

    .fwsxy {
        // padding-bottom: 31px;
        font-size: 12px;
        color: #9e9e9e;

        span {
            color: #1c87f3;
        }
    }
}

::v-deep .el-radio.is-bordered {
    display: flex;
    align-items: center;
    padding-top: 0;
}

.applying {
    display: flex;
    justify-content: center;
    padding: 80px 0 229px 0;

    .zxkf {
        padding-top: 20px;
        font-size: 12px;
        color: #9e9e9e;

        i {
            color: #1c87f3;
        }
    }
}

.applying ::v-deep .el-result__title {
    position: relative;
    left: 10px;
    padding-bottom: 12px;
    font-size: 24px;
    font-weight: 600;
    color: #333333;
}

::v-deep .el-result__icon svg {
    width: 100px;
    height: 100px;
}

.service-info {
    .info-item {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 8px 0;
    }

    .label {
        width: 123px;
        font-size: 14px;
        color: #333333;
        text-align: right;
        padding-right: 8px;
    }

    .but {
        padding-left: 18px;
    }
}

.serviceType {
    display: flex;
    align-items: flex-end;

    ::v-deep .el-radio__input {
        display: none;
    }

    ::v-deep .el-radio {
        margin-right: 10px;
    }
}

.tip {
    font-size: 12px;
    text-decoration: underline;
    color: #333333;
    margin-bottom: 3px;
    cursor: pointer;

    &:hover {
        color: #1c87f3;
    }
}

.bzj {
    position: relative;

    i {
        font-size: 12px;
        position: absolute;
        top: 2px;
        right: -6px;
    }
}
</style>./applyservice.vue